package com.mhuang.wechat.common.utils;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

/**
 * 
 * @Package: com.mhuang.wechat.common.utils
 * @Description 拼音处理工具类（引用pinyin4j)
 * @author huang.miao
 * @date 2017年4月12日 下午4:43:17  
 * @since 1.0.0
 * @group skiper-opensource
 */
public class PinyinUtils {

	public static String getFirstPinYin(String chinese){
		try{
			return getFirstSpell(chinese).substring(0, 1);
		}catch(Exception e){
			return "";
		}
		
	}
	/** 
     * 获取汉字串拼音首字母，英文字符不变 
     * @param chinese 汉字串 
     * @return 汉语拼音首字母 
     */ 
    public static String getFirstSpell(String chinese) { 
        StringBuffer pybf = new StringBuffer(); 
        char[] arr = chinese.toCharArray(); 
        HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat(); 
        defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE); 
        defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE); 
        String[] temp = null;
        for (int i = 0; i < arr.length; i++) { 
            if (arr[i] > 128) { 
                try { 
                    temp = PinyinHelper.toHanyuPinyinStringArray(arr[i], defaultFormat); 
                    if (temp != null) { 
                        pybf.append(temp[0].charAt(0)); 
                    } 
                } catch (BadHanyuPinyinOutputFormatCombination e) { 
                    e.printStackTrace(); 
                } catch(Exception e){
                	continue;
                }
            } else { 
                pybf.append(arr[i]); 
            } 
        } 
        return pybf.toString().replaceAll("\\W", "").trim(); 
    } 

    /** 
     * 获取汉字串拼音，英文字符不变 
     * @param chinese 汉字串 
     * @return 汉语拼音 
     */ 
    public static String getFullSpell(String chinese) { 
        StringBuffer pybf = new StringBuffer(); 
        char[] arr = chinese.toCharArray(); 
        HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat(); 
        defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE); 
        defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE); 
        for (int i = 0; i < arr.length; i++) { 
            if (arr[i] > 128) { 
                try { 
                    pybf.append(PinyinHelper.toHanyuPinyinStringArray(arr[i], defaultFormat)[0]); 
                } catch (BadHanyuPinyinOutputFormatCombination e) { 
                    e.printStackTrace(); 
                } 
            } else { 
                pybf.append(arr[i]); 
            } 
        } 
        return pybf.toString(); 
    }
}
